package oop.ex3.serverprotocol;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import oop.ex3.nameserver.NameServer;
import oop.ex3.sharedclasses.IPaddress;

/**
 * Handles GOAWAY Message.
 * handles a client's request to shut a server down.
 * 
 * 
 * @author zablo
 *
 */
public class GoAway extends ClientMessageHandler{

	@Override
	public boolean run(NameServer server, IPaddress sessionIP,
			DataInputStream clientInput, DataOutputStream clientOutput) {
		// TODO ASK @ FORUM
		/*
		 * In case we got a GOAWAY, the server should stop getting new requests.
		 * should it stop the moment it gets the GOAWAY?
		 * or after the DONE-ENDSESSION-DONE is processed?
		 */
		
		// ASSUMING the request stop happens after the DONE-ENDSESSION-DONE
		
		if (endsWithEnd(clientInput)==FAILURE){ //doesn't end with END
			return FAILURE;
		}
		
		if (ServerMessageSender.done(clientOutput)==FAILURE){ //sends DONE
			return FAILURE;
		}
		
		try {
			if (!clientInput.readUTF().equals(ClientMessageHandler.END_SESSION)){
				// Illegal message after GOAWAY, only ENDSESSION allowed.
				return FAILURE;
			}
			
			if (ServerMessageSender.done(clientOutput)==FAILURE){//sends DONE
				return FAILURE;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return FAILURE;
		}
		synchronized (server) {
			server.setOffline();
		}

		return SUCCESS;

}
}
